package web;

import com.fasterxml.jackson.databind.ObjectMapper;
import service.UserService;
import service.impl.UserServiceImpl;
import util.EncryptUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        ObjectMapper om = new ObjectMapper();
        Map<String,Object> message =new HashMap<>(8);
        UserService us = new UserServiceImpl();
        if(us.checkPassowrd(username,password)){
            //储存到cookies 采用md5加密
            Cookie cookiePassword = new Cookie("PWM", EncryptUtil.getMD5Str(password));
            Cookie cookieUsername = new Cookie("UNM", EncryptUtil.getMD5Str(username));
            Cookie cookieuid = new Cookie("uid",""+us.getUserInfo(username).getUid());
            //储存1个月
            cookiePassword.setMaxAge(60*60*24*30);
            cookieUsername.setMaxAge(60*60*24*30);
            cookieuid.setMaxAge(60*60*24*30);
            //存储
            response.addCookie(cookiePassword);
            response.addCookie(cookieUsername);
            response.addCookie(cookieuid);

            message.put("msg","登录成功");
            message.put("state",true);
            om.writeValue(response.getOutputStream(),message);
        }else {
            message.put("msg","账号或密码错误");
            message.put("state",false);
            om.writeValue(response.getOutputStream(),message);
        }

    }

}
